package com.datacollection.datacollectionsystem.utils;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Optional;

/**
 * Screenshoter
 *
 * @author liupf
 * @date 2018/12/5
 */
public class Screenshoter {
    private static final String SCREENSHOT_PATH = "./screenshot/";
    private static final String SCREENSHOT_NAME_FORMAT = "%s.png";

    private Screenshoter() {
        throw new IllegalStateException("utility class");
    }

    /**
     * take screenshot
     */
    public static void take(WebDriver driver) {
        Optional.ofNullable(driver)
                .map(TakesScreenshot.class::cast)
                .map(takesScreenshot -> takesScreenshot.getScreenshotAs(OutputType.FILE))
                .ifPresent(screenshot -> {
                    try {
                        File saveFile = new File(SCREENSHOT_PATH + String.format(SCREENSHOT_NAME_FORMAT, LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"))));
                        FileUtils.copyFile(screenshot, saveFile);
                    } catch (IOException e) {
                        System.out.print(e);
                    }
                });
    }
}
